import redis


class RedisHelper:

    def __init__(self, host='127.0.0.1', port=6379, password=None, db=0):
        self.__redis = None
        self.host = host
        self.port = port
        self.password = password
        self.db = db

    def connect(self):
        self.__redis = redis.StrictRedis(host=self.host, port=self.port, password=self.password, db=self.db)

    def set(self, key, value):
        self.__redis.set(key, value)

    # 获取key-value
    def get(self, key):
        return self.__redis.get(key).decode()

    # 获取key-value
    def hget(self, key, field):
        return self.__redis.hget(key, field).decode()

    # 获取key-value
    def hset(self, key, field, value):
        return self.__redis.hset(key, field, value)

    # 获取hashtable中所有的值
    def hget_all(self, key):
        res = self.__redis.hgetall(key)
        for k in res:
            res[k] = res[k].decode()
        return res

    # 判断key是否存在
    def isExists(self, key):
        # 返回1存在，0不存在
        return self.__redis.exists(key)

    # 添加集合操作
    def addSet(self, key, value):
        # 集合中存在该元素则返回0,不存在则添加进集合中，并返回1
        # 如果key不存在，则创建key集合，并添加元素进去,返回1
        return self.__redis.sadd(key, value)

    # 判断value是否在key集合中
    def isSetExists(self, key, value):
        # 判断value是否在key集合中，返回布尔值
        return self.__redis.sismember(key, value)

    # 给key设置过期时间，单位秒
    def expire(self, key, seconds):
        return self.__redis.expire(key, seconds)

    def zrange(self, key, start_index, end_index):
        return self.__redis.zrange(key, start_index, end_index)
    
    def get_message(self, key):
        print(f'get_message :{key}...')
        data_list = self.zrange(key, 0, -1)
        if len(data_list) > 0:
            data = data_list[0]
            self.__redis.zrem(key, data)
            return data

    def zadd_message(self, key, message):
        return self.__redis.zadd(key, {message: 9})

    # 关闭连接
    def close(self):
        self.__redis.close()
